<?php

declare(strict_types=1);

namespace app\validate\api\admin\system;

use app\validate\api\ApiBaseValidate;
use app\model\api\admin\system\Dept;

class DeptValidate extends ApiBaseValidate
{
    protected $ex_data = [
    ];

    protected $rule = [
        'id' => 'require|integer',
        'parent_id' => 'require|integer|egt:0|isParentIdValid',
        'name' => 'require|max:255',
        'principal' => 'max:32',
        'phone' => 'max:20|mobile',
        'email' => 'max:128|email',
        'sort' => 'integer',
        'status' => 'require|in:0,1',
        'remark' => 'max:255',


        // 扩展
        'del_ids' => 'require|regex:ids',
    ];

    protected $message = [];

    protected $scene = [
        'save' => ['parent_id', 'name', 'principal', 'phone', 'email', 'sort', 'status', 'remark'],
        'update' => ['id', 'parent_id', 'name', 'principal', 'phone', 'email', 'sort', 'status', 'remark'],
    ];

    public function sceneDelete()
    {
        return $this->only(
            [
                'del_ids',
            ]
        )->append('del_ids', 'hasChild');
    }

    protected function hasChild($value, $rule, $data = [])
    {
        $m = Dept::where([
            ['parent_id', 'in', $data['del_ids']]
        ])
            ->field('id')
            ->select();

        if (!$m->isEmpty()) {
            return '存在子部门，无法删除';
        }
        return true;
    }

    protected function isParentIdValid($value, $rule, $data = [], $field = '', $title = '')
    {
        // 为了方便处理所有子级,调整为只支持一个根父级,或只有超管才能选择根父级
        if ($value == 0) {
            return is_super_admin() ? true : '请选择一个父级';
        }

        $targetDept = Dept::where([
            ['id', '=', $value],
            ['status', '=', Dept::STATUS_NOMAL],
        ])->find();

        if (!$targetDept) {
            return '所选父级部门不存在或已禁用';
        }

        // // 检查部门层级深度限制
        // if ($targetDept->parent_ids) {
        //     $levels = count(explode(',', $targetDept->parent_ids)) + 1;
        //     if ($levels > 7) { // 假设最大层级为7层
        //         return '部门层级不能超过7层';
        //     }
        // }

        if (isset($data['id']) && $data['id'] != '') {
            // 检查不能选自己作为父级
            if ($data['id'] == $data['parent_id']) {
                return '不能选择自己作为父级';
            }

            // 检查不能选择自己的子级作为父级
            $currentDept = Dept::where('id', $data['id'])->find();
            if ($currentDept) {
                // 获取原部门的完整路径
                $path = $currentDept->parent_ids ? $currentDept->parent_ids . ',' . $currentDept->id : $currentDept->id;

                // 检查目标父级是否是当前部门的子级
                // $targetDept = Dept::where('id', $value)->find();
                if ($targetDept && $targetDept->parent_ids) {
                    $targetPath = $targetDept->parent_ids . ',' . $targetDept->id;
                    if (strpos($targetPath, (string) $path) === 0) {
                        return '不能选择子部门作为父级';
                    }
                }

                // 检查父级部门名称是否重复
                $existsSameName = Dept::where([
                    ['parent_id', '=', $value],
                    ['id', '<>', $data['id']],
                    ['name', '=', $data['name']]
                ])->find();

                if ($existsSameName) {
                    return '同一父级下已存在相同名称的部门:' . $data['name'];
                }
            }
        } else {
            // 新增时检查部门名称是否重复
            $existsSameName = Dept::where([
                ['parent_id', '=', $value],
                ['name', '=', $data['name']]
            ])->find();

            if ($existsSameName) {
                return '同一父级下已存在相同名称的部门:' . $data['name'];
            }
        }

        return true;
    }
}
